package com.zcxy360.sandtable.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;


public class JavacvUtil {

	public static void generateThumbnail(String videoPath, String thumbnailPath) {
	    File targetFile = new File(thumbnailPath);
	    try {
			targetFile.createNewFile();
			FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoPath); 
			ff.start();
			int lenght = ff.getLengthInFrames();
			int i = 0;
			Frame f = null;
			while (i < lenght) {
			    // 过滤前5帧，避免出现全黑的图片，依自己情况而定
			    f = ff.grabFrame();
			    if ((i > 5) && (f.image != null)) {
			        break;
			    }
			    i++;
			}
			int width = f.image.width();
			int height = f.image.height();
			BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
			bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
			        0, 0, null);
			ImageIO.write(bi, "jpg", targetFile);
			ff.stop();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}

	public static Map<String,Object> getInfo(String path){
		Map<String,Object> info = new HashMap<>();
		FFmpegFrameGrabber ff = new FFmpegFrameGrabber(path); 
		try {
			ff.start();
			info.put("duration", ff.getLengthInTime()/1000000);
			info.put("frameRate", ff.getFrameRate());
			info.put("resolution", ff.getImageWidth()+"x"+ff.getImageHeight());
			ff.stop();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		return info;
	}

	public static Map<String, Object> generateThumbnailAndGetInfo(String path) {
		String thumbnailPath = path.replace(path.substring(path.lastIndexOf(".")), ".jpg");
		generateThumbnail(path,thumbnailPath);
		Map<String, Object> info = getInfo(path);
		info.put("thumbnailPath", thumbnailPath);
		return info;
	}

}
